package Persistance;

import sun.misc.BASE64Encoder;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;

public class PasswordService {
      private static Logger logger = Logger.getLogger("MovieSystem.Persistance.PasswordService");

    //Java Code that Implements One-way Hash Algorithm
    public static String encrypt(String plaintext) throws NoSuchAlgorithmException {
        MessageDigest md;
        try  {
            //Java security API obtaining an instance of a message digest object using the algorithm supplied
            //  (in this case, SHA-1 message digest algorithm will be used)
            md = MessageDigest.getInstance("SHA");
        }
        catch(NoSuchAlgorithmException e)  {
            logger.error("unable to encrypt password"+e.getMessage());
            throw new NoSuchAlgorithmException (e.getMessage()) ;
        }
        try  {
            //convert the plaintext  into a byte-representation using UTF-8 encoding format.
            // and apply this array to the message digest object created earlier.
            // .This array will be used as a source for the message digest object to operate on.... .
            md.update(plaintext.getBytes("UTF-8"));
        }
        catch(UnsupportedEncodingException e)  {
            logger.error("unable to encrypt password"+e.getMessage());
            throw new NoSuchAlgorithmException (e.getMessage());
        }
        byte raw[] = md.digest(); //Do the transformation: generate an array of bytes that represent the digested (encrypted) password value.
        return (new BASE64Encoder()).encode(raw); //Create a String representation of the byte array representing the digested password value. This is needed to be able to store the password in the database.
    }

    public static boolean compare( String plaintext, String encrypedText) throws NoSuchAlgorithmException {
         return encrypedText.equals(encrypt(plaintext));
    }
}
